<?php

namespace Ibw\JobeetBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Ibw\JobeetBundle\Entity\Category;

/**
 * Category controller. 
 *
 * @Route("/category", name="ibw_category")
 */
class CategoryController extends Controller {

    /**
     * Finds and displays a Category entity.
     *
     * @Route("/{_locale}/{slug}/{page}", name="ibw_category_show")
     * @Method("GET")
     */
    public function showAction($slug, $page) {
        $em = $this->getDoctrine()->getManager();

        $category = $em->getRepository('IbwJobeetBundle:Category')->findOneBySlug($slug);

        if (!$category) {
            throw $this->createNotFoundException('Unable to find Category entity.');
        }

        $latestJob = $em->getRepository('IbwJobeetBundle:Job')->getLatestPost($category->getId());

        if ($latestJob) {
            $lastUpdated = $latestJob->getCreatedAt()->format(DATE_ATOM);
        } else {
            $lastUpdated = new \DateTime();
            $lastUpdated = $lastUpdated->format(DATE_ATOM);
        }

        $total_jobs = $em->getRepository('IbwJobeetBundle:Job')->countActiveJobs($category->getId());
        $jobs_per_page = $this->container->getParameter('max_jobs_on_category');
        $last_page = ceil($total_jobs / $jobs_per_page);
        $previous_page = $page > 1 ? $page - 1 : 1;
        $next_page = $page < $last_page ? $page + 1 : $last_page;
        $category->setActiveJobs($em->getRepository('IbwJobeetBundle:Job')->getActiveJobs($category->getId(), 
                $jobs_per_page, ($page - 1) * $jobs_per_page));

        $format = $this->getRequest()->getRequestFormat();

        return $this->render('IbwJobeetBundle:Category:show.' . $format . '.twig', array(
                    'category' => $category,
                    'last_page' => $last_page,
                    'previous_page' => $previous_page,
                    'current_page' => $page,
                    'next_page' => $next_page,
                    'total_jobs' => $total_jobs,
                    'feedId' => sha1($this->get('router')->generate('ibw_category_show', array('slug' => $category->getSlug(), 
                        'page' => $page, '_format' => 'atom'), true)),
                    'lastUpdated' => $lastUpdated
        ));
    }

}
